package com.yopuo.web.config.oss;

import com.aliyun.oss.OSSClient;
import com.yopuo.common.config.OssAliyunConfig;
import com.yopuo.common.exception.oss.OssException;
import org.springframework.beans.factory.annotation.Value;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * 阿里云存储
 *
 * @author Mark sunlightcs@gmail.com
 */
public class AliyunCloudStorageService extends CloudStorageService {

    private OSSClient client;

    public AliyunCloudStorageService(){
        //初始化
        init();
    }

    private void init(){
        client = new OSSClient(OssAliyunConfig.getEndPoint(), OssAliyunConfig.getAccessKeyId(), OssAliyunConfig.getAccessKeySecret());
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            client.putObject(OssAliyunConfig.getBucketName(), path, inputStream);
        } catch (Exception e){
            throw new OssException("上传文件失败，请检查配置信息", e);
        }

        return OssAliyunConfig.getDomain() + "/" + path;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(OssAliyunConfig.getPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(OssAliyunConfig.getPrefix(), suffix));
    }
}
